<template>
	<view style="background-color: #f2f2f2;position: relative;">
		<view ref="fixedTop" style="position: fixed;top:0;z-index: 99;">
			<com-nav-bar :fixed="true" @clickLeft="back" left-icon="back" title="确认订单"></com-nav-bar>
			<tui-list-cell :arrow="true" :last="true" :radius="true" @click="chooseAddr" v-if="addressVisible&&submitForm.source_type != 'easy_oil'">
				<view class="tui-address">
					<view v-if="user_address && user_address.length != 0">
						<view class="tui-userinfo">
							<text class="tui-name">{{user_address.name}}</text> {{user_address.mobile}}
						</view>
						<view class="tui-addr">
							<text>{{user_address.province}}{{user_address.city}}{{user_address.district}}{{user_address.detail}}</text>
						</view>
					</view>
					
					<view class="tui-none-addr" v-else>
						<text>请添加收货地址</text>
						<!-- #ifdef H5 -->
						<button type="default"
							style="width: 250rpx;font-size: 25rpx;margin-left: 140rpx;background: rgb(255, 113, 4);color: #fff;"
							@click.stop="getWechatAddress">获取微信收货地址</button>
						<!--#endif -->
						<!-- #ifdef MP-WEIXIN-->
						<button type="default"
							style="width: 250rpx;font-size: 25rpx;margin-left: 140rpx;background: rgb(255, 113, 4);color: #fff;"
							@click.stop="getMPAddress">获取微信收货地址</button>
						<!--#endif -->
					</view>
					
				</view>
			</tui-list-cell>
		</view>
		
		<view style="background-color: #fff;padding: 0rpx 10rpx 100rpx;" :style="{marginTop:fixedTopHeight+10+'px'}">
			
			<view v-for="item in orderDetails" :key="item.attr_id" style="margin-bottom: 20rpx;">
				<view style="display: flex;" @click="showDeductDetails(item)">
					<image style="width: 200rpx;height: 200rpx;margin-right: 20rpx;flex-shrink:0;" lazy-load="true" :src="jsonFormat(item.extend).cover_pic"></image>
					<view style="height:200rpx;display: flex;flex-direction: column;justify-content: space-between;flex-grow: 1;">
						<view v-line-clamp='1' style="font-size: 28rpx;height: 28rpx;line-height: 28rpx;">{{jsonFormat(item.extend).goods_name}}</view>
						<view v-line-clamp='1' style="font-size: 10pt;color: #909399;">{{jsonFormat(item.extend).attr_str}}</view>
						<view style="font-size: 10pt;">
							<text>单价：</text>
							<text style="text-decoration: line-through;font-size: 9pt;color:#909399">￥{{jsonFormat(item.extend).original_price}}</text>
							<text style="font-weight: 600;">￥{{item.unit_price}}</text>
						</view>
						<view style="font-size: 12pt;">
							<text style="font-weight: 600;margin-right: 20rpx;">x{{item.goods_num}}</text>
							<text style="color:red">小计：{{item.price}}</text>
						</view>
						<view style="font-size: 10pt;text-align: right;">点击查看详情 >></view>
					</view>
				</view>
			</view>
			
			<view style="padding: 20rpx;" v-if="order">
				<view style="display: flex;justify-content: space-between;padding: 20rpx 10rpx;">
					<view>商品总计：</view>
					<view style="color:red">￥{{order.goods_price}}</view>
				</view>
				<view style="display: flex;justify-content: space-between;padding: 20rpx 10rpx;" @click="TotalFreightsVisible = true">
					<view>运费总计：</view>
					<view :style="{color: order.express_price < 0 ? 'green' : 'red'}">
						<u-icon style="margin-right: 10rpx;color:#909399" size="15pt" name="question-circle-fill"></u-icon>
						<text>￥{{order.express_price}}</text>
					</view>
				</view>
				<view style="display: flex;justify-content: space-between;padding: 20rpx 10rpx;" @click="TotalDeductsVisible = true">
					<view>抵扣总计：</view>
					<view :style="{color: order.deduct_price < 0 ? 'green' : 'red'}" style="display: flex;align-items: center;">
						<u-icon style="margin-right: 10rpx;color:#909399" size="15pt" name="question-circle-fill"></u-icon>
						<text>￥{{order.deduct_price}}</text>
					</view>
				</view>
			</view>
		
		
			<view style="padding: 20rpx;" v-if="Object.keys(showDeductTypeList).length > 0">
				<view style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 20rpx;background-color: #f2f2f2;padding: 20rpx;" v-for="(item,index) in showDeductTypeList" :key="index">
					<view>{{index | deductTypeDesc}}</view>
					<view>
						<switch style="transform:scale(0.7)" :disabled="item.toggle == 0" :checked="submitForm.deduct_status[index] == 1" @change="deductStatusChange($event,index)" />
					</view>
				</view>
			</view>
		</view>
		
		
		<!-- 订单子项商品详情 -->
		<u-popup v-model="deductDetailsVisible" mode="top" closeable length="100%" @close="closeDeductDetails">
			<view style="padding: 100rpx 20rpx 0;">
				<view style="display: flex;padding: 20rpx;background-color: #f2f2f2;border-radius: 10rpx;">
					<image style="width: 200rpx;height: 200rpx;margin-right: 20rpx;flex-shrink:0;" lazy-load="true" :src="jsonFormat(showDetail.extend).cover_pic"></image>
					<view style="height:200rpx;display: flex;flex-direction: column;justify-content: space-between;flex-grow: 1;">
						<view v-line-clamp='2' style="font-size: 28rpx;height: 56rpx;line-height: 28rpx;">{{jsonFormat(showDetail.extend).goods_name}}</view>
						<view v-line-clamp='1' style="font-size: 10pt;color: #909399;">{{jsonFormat(showDetail.extend).attr_str}}</view>
						<view style="font-size: 10pt;">
							<text>单价：</text>
							<text style="text-decoration: line-through;font-size: 9pt;color:#909399">￥{{jsonFormat(showDetail.extend).original_price}}</text>
							<text style="font-weight: 600;">￥{{showDetail.unit_price}}</text>
						</view>
						<view style="font-size: 12pt;">
							<text style="font-weight: 600;margin-right: 20rpx;">x{{showDetail.goods_num}}</text>
							<text style="color:red">小计：{{showDetail.price}}</text>
						</view>
					</view>
				</view>
				<view style="margin-top: 40rpx;">
					<view style="font-size: 14pt;font-weight: 600;">其他费用</view>
					
					<!-- 抵扣相关 -->
					<template v-if="showDetail.deducts && showDetail.deducts.length > 0">
						<view style="font-size: 9pt;color: red;padding: 20rpx 0;">启用的抵扣在订单确认提交时，将会从账户进行扣除。<br/>订单未在指定时间内付款，系统将自动退还。<br/> 无法操作的抵扣项为必须扣除项。</view>
						<view v-for="(item,index) in showDetail.deducts" :key="index" style="background-color: #f2f2f2;border-radius: 10rpx;padding: 20rpx;margin-bottom: 20rpx;">
							<view style="display: flex;justify-content: space-between;align-items: center;">
								<view>{{item.source_type| deductTypeDesc}}</view>
							</view>
							<view style="padding: 20rpx;text-align: center;">
								<view :style="{color: item.deduct_price <= 0 ? 'green' : 'red'}" style="font-size: 16pt;font-weight: 600;">
									<text>{{item.deduct_price.toFixed(2)}}</text>
								</view>
								<view style="font-size: 9pt;color: #909399;">抵扣金额</view>
							</view>
							<view style="font-size: 10pt;">{{item.desc}}</view>
						</view>
					</template>

					<!-- 运费相关 -->
					<template v-if="showDetail.freights && showDetail.freights.length > 0">
						<view style="font-size: 9pt;color: red;padding: 20rpx 0;">费用可能包含其他子项商品，相同商品不同规格自动合并计算运费。</view>
						<view v-for="(item,index) in showDetail.freights" :key="index" style="background-color: #f2f2f2;border-radius: 10rpx;padding: 20rpx;margin-bottom: 20rpx;">
							<view style="display: flex;justify-content: space-between;align-items: center;font-size: 9pt;">
								<view>按件计费</view>
								<view>{{jsonFormat(item.extend).freight_name}}</view>
							</view>
							<view style="display: flex;justify-content: space-between;align-items: center;">
								<view>数量：{{item.goods_num}}</view>
								<view :style="{color: item.price <= 0 ? 'green' : 'red'}" style="font-size: 16pt;font-weight: 600;">
									<text>{{item.price.toFixed(2)}}</text>
								</view>
							</view>
						</view>
					</template>
					
				</view>
			</view>
		</u-popup>
		
		
		<!-- 所有子项的抵扣信息 -->
		<u-popup v-model="TotalDeductsVisible" mode="top" closeable length="100%">
			<view style="padding: 100rpx 20rpx 0;">
				<template v-if="deducts && deducts.length > 0">
					<view style="font-size: 9pt;color: red;padding: 20rpx 0;">启用的抵扣在订单确认提交时，将会从账户进行扣除。<br/>订单未在指定时间内付款，系统将自动退还。<br/> 无法操作的抵扣项为必须扣除项。</view>
					<view v-for="(item,index) in deducts" :key="index" style="background-color: #f2f2f2;border-radius: 10rpx;padding: 20rpx;margin-bottom: 20rpx;">
						<view style="display: flex;justify-content: space-between;align-items: center;">
							<view>{{item.source_type| deductTypeDesc}}</view>
						</view>
						<view style="padding: 20rpx;text-align: center;">
							<view :style="{color: item.deduct_price <= 0 ? 'green' : 'red'}" style="font-size: 16pt;font-weight: 600;">
								<text>{{item.deduct_price.toFixed(2)}}</text>
							</view>
							<view style="font-size: 9pt;color: #909399;">抵扣金额</view>
						</view>
						<view style="font-size: 10pt;">{{item.desc}}</view>
					</view>
				</template>
				<template v-else>无</template>	
			</view>
		</u-popup>
		
		
		<!-- 所有子项的运费信息 -->
		<u-popup v-model="TotalFreightsVisible" mode="top" closeable length="100%">
			<view style="padding: 100rpx 20rpx 0;">
				<template v-if="freights && freights.length > 0">
					<view style="font-size: 9pt;color: red;padding: 20rpx 0;">单项费用可能包含多项商品，相同商品不同规格自动合并计算运费。</view>
					<view v-for="(item,index) in freights" :key="index" style="background-color: #f2f2f2;border-radius: 10rpx;padding: 20rpx;margin-bottom: 20rpx;">
						<view style="display: flex;justify-content: space-between;align-items: center;font-size: 9pt;">
							<view>按件计费</view>
							<view>{{jsonFormat(item.extend).freight_name}}</view>
						</view>
						<view style="display: flex;justify-content: space-between;align-items: center;">
							<view>数量：{{item.goods_num}}</view>
							<view :style="{color: item.price <= 0 ? 'green' : 'red'}" style="font-size: 16pt;font-weight: 600;">
								<text>{{item.price.toFixed(2)}}</text>
							</view>
						</view>
					</view>
				</template>
				<template v-else>无</template>
			</view>
		</u-popup>
		
		
		
		<view class="fixed-bottom">
			<view style="padding-right: 20rpx;color: #BC0100;display: flex;align-items: flex-end;padding-right: 0;" :style="{color:'#FF7104'}">
				<view style="color: #222;line-height: 30rpx;">合计: </view>
				<view style="font-size: 26rpx;line-height: 26rpx;">￥</view>
				<view style="font-size: 34rpx;line-height: 32rpx;font-weight: 600;">{{order.pay_price}}</view>
			</view>
			<view class="tui-pr25" @tap="submitOrder" :style="{background:'#FF7104'}">去支付</view>
		</view>
	</view>
</template>

<script>
	let that;
	import tuiListCell from "@/components/list-cell/list-cell"
	export default {
		components: {
			tuiListCell,
		},
		data(){
			return {
				addressVisible: true,//地址是否显示
				source_type: '',	//订单类型
				user_address: '', //用户地址
				fixedTopHeight:0,//顶部固定定位高度
				
				//订单预览和提交的参数
				submitForm:{ 
					cart_ids:[],
					address_id:0,
					attr_id:0,
					goods_num:0,
					source_type:'',//订单关联类型
					source_id:'',//关联类型ID
					deduct_status: {
						deductByOverflow:1,//是否使用满减抵扣
						deductByRedPack:1,//是否使用红包抵扣
						deductByScore:1,//是否使用积分抵扣
						deductByQuota:1,//是否使用名额抵扣
						deductByShopVoucher:1,//是否使用购物券抵扣
					},
				},
				
				
				showDeductTypeList:{},//需要展示的抵扣控件
				deductDetailsVisible:false,
				showDetail:{},
				TotalDeductsVisible:false,
				TotalFreightsVisible:false,
				
				
				
				//订单预览所需
				order:'',//主订单信息
				orderDetails:'',//订单详情信息
				freights:'',//运费信息
				deducts:'',//抵扣信息
				
				
			}
		},
		beforeCreate(){
			that = this;
		},
		onShow(){
			this.$nextTick(function(){
				that.fixedTopHeight = Math.ceil(that.$refs.fixedTop.$el.clientHeight);
			})
		},
		async onLoad(opt) {
			this.submitForm.cart_ids = this.jsonFormat(opt.cart_ids);
			
			//获取用户默认地址
			await this.getDefaultAddress();
			// await this.orderPreview();
		},
		computed: {
			jsonFormat(){
				return data => {
					if( typeof data == 'string'){
						data = JSON.parse(data);
					}
					return data ?? {};
				}
			},
		},
		filters: {
			deductTypeDesc(type) {
				const descMaps = {
					'deductByOverflow':'满减活动抵扣',
					'deductByRedPack':'红包抵扣',
					'deductByScore':'积分抵扣',
					'deductByQuota':'库存名额抵扣',
					'deductByShopVoucher':'购物券抵扣'
				};
				return descMaps[type] || '未知';
			},
		},
		watch:{
			user_address:{
				handler(val){
					if(val && val.id > 0){
						this.submitForm.address_id = val.id;
						this.orderPreview();
					}
				},
				immediate:true
			}
		},
		methods:{
			back(){
				this.navBack()
			},
			
			//切换收货地址
			chooseAddr() { //选择地址
				uni.navigateTo({
					url: "/pages/user/address/list?name=cart"
				});
			},
			
			//获取用户默认收货地址
			async getDefaultAddress(){
				const res = await this.$http.request({
					url: this.$api.user.defaultAddress,
					method: 'get',
					showLoading:true,
				});
				if(res.code !== 0){
					return this.$http.toast(res.msg);
				}
				this.user_address = res.data;
			},
			
			//订单商品信息查看
			showDeductDetails(detail){
				that.showDetail = detail;
				that.showDetail.deducts = [];
				if(that.deducts){
					that.deducts.map(item =>{
						if(item.union_id == that.showDetail.attr_id){
							
							that.showDetail.deducts.push(item);
						}
					})
				}
				that.showDetail.freights = [];
				if(that.freights){
					that.freights.map(item => {
						if(item.goods_id == that.showDetail.goods_id){
							that.showDetail.freights.push(item);
						}
					})
				}
				console.log('show',that.showDetail)
				that.deductDetailsVisible = true;
			},
			closeDeductDetails(){
				that.showDetail = {};
			},
			
			
			//抵扣控件状态切换
			deductStatusChange(opt,type){
				this.submitForm.deduct_status[type] = opt.detail.value ? 1 : 0;
				this.orderPreview()
			},
			
			
			//订单预览
			async orderPreview(){
				that.submitForm.address_id = that.user_address.id;
				const res = await that.$http.request({
					url: that.$api.v2Order.preview,
					method: 'post',
					data:that.submitForm,
					showLoading:true,
				});
				if(res.code !== 0){
					return that.$http.toast(res.msg);
				}
				that.order = res.data.order;//主订单信息，订单总价格，总运费，总抵扣等信息。
				that.orderDetails = res.data.orderDetails;//订单商品信息
				that.freights = res.data.freights;//订单商品运费信息
				that.deducts = res.data.deducts;//订单抵扣信息
				that.submitForm.deduct_status = res.data.deductStatus;
				
				
				
				let keys = Object.keys(that.submitForm.deduct_status);//获取允许的所有抵扣类型
				that.showDeductTypeList = {};//需要展示的抵扣状态控件
				//遍历抵扣信息，将抵扣状态转换成 bool,并赋值需要展示的抵扣控件
				that.deducts.map((item,index) =>{
					that.deducts[index].deduct_status = Boolean(item.deduct_status);
					if( keys.indexOf(item.source_type) > -1 ){
						that.showDeductTypeList[item.source_type] = that.showDeductTypeList[item.source_type] ?? {};
						that.showDeductTypeList[item.source_type].is_show = true;
						//是否允许抵扣控件自由切换，只要有一个子项抵扣不允许切换，则所有对应类型的子项都不允许切换
						that.showDeductTypeList[item.source_type].toggle = item.toggle && (that.showDeductTypeList[item.source_type].toggle ?? 1);
					}
				});

			},
			
			
			//订单提交
			async submitOrder(){
				that.submitForm.address_id = that.user_address.id;
				const res = await that.$http.request({
					url: that.$api.v2Order.submit,
					method: 'post',
					data:that.submitForm,
					showLoading:true,
				});
				if(res.code !== 0){
					return that.$http.toast(res.msg);
				}
				uni.navigateTo({
					url:'/pages/order/payment/preview?order_no=' + res.data.order_no
				})
			},
			
		}
	}
</script>

<style lang="scss">
	.tui-address {
		min-height: 80rpx;
		padding: 10rpx 0;
		box-sizing: border-box;
		position: relative;
	}
	.tui-userinfo {
		font-size: 30rpx;
		font-weight: 500;
		line-height: 30rpx;
		padding-bottom: 12rpx;
	}
	.tui-name {
		padding-right: 40rpx;
	}
	.tui-addr {
		font-size: 24rpx;
		word-break: break-all;
		padding-right: 25rpx;
	}
	.tui-none-addr {
		height: 80rpx;
		padding-left: 5rpx;
		display: flex;
		align-items: center;
	}
	
	
	
	.fixed-bottom{
		position: fixed;
		bottom: 0;
		z-index: 999;
		background-color: #fff;
		width: 100vw;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		border-top: 0rpx solid transparent;
		box-shadow: 0 -2rpx 4rpx -2rpx rgba(0, 0, 0, 0.5); /* 上边框的阴影 */
	}
	
	
	
	
	
	.tui-pr25 {
		background: linear-gradient(-30deg, rgba(214, 16, 13, 1), rgba(241, 72, 34, 1));
		width: 208rpx;
		height: 78rpx;
		border-radius: 50rpx;
		color: #FFFFFF;
		font-size: 11pt;
		text-align: center;
		line-height: 78rpx;
	}
</style>